import service from './service'
import { CONTENT_TYPE } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { blobValidate } from '@/utils'
import { saveAs } from 'file-saver'
import { ElLoading } from 'element-plus'

const request = (option: AxiosConfig) => {
  const { url, method, params, data, headers, responseType } = option
  const userStore = useUserStoreWithOut()
  return service.request({
    url: url,
    method,
    params,
    data,
    responseType: responseType,
    headers: {
      'Content-Type': CONTENT_TYPE,
      [userStore.getTokenKey ?? 'Authorization']: userStore.getToken ?? '',
      ...headers
    }
  })
}

export default {
  get: <T = any>(option: AxiosConfig) => {
    return request({ method: 'get', ...option }) as Promise<IResponse<T>>
  },
  post: <T = any>(option: AxiosConfig) => {
    return request({ method: 'post', ...option }) as Promise<IResponse<T>>
  },
  delete: <T = any>(option: AxiosConfig) => {
    return request({ method: 'delete', ...option }) as Promise<IResponse<T>>
  },
  put: <T = any>(option: AxiosConfig) => {
    return request({ method: 'put', ...option }) as Promise<IResponse<T>>
  },
  exportFile: async (option: {
    method?: AxiosConfig['method']
    url: AxiosConfig['url']
    params: AxiosConfig['params']
    filename: string
    _config?: AxiosConfig
  }) => {
    const { method = 'get', url, params, filename, _config } = option
    const downloadLoadingInstance = ElLoading.service({
      text: '正在导出文件，请稍候',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    try {
      const response = (await request({
        method,
        url,
        ...(method === 'get' ? { params } : { data: params }),
        ...{
          responseType: 'blob',
          ..._config
        }
      })) as IResponse<Blob>
      // 验证是否为 Blob 对象
      // 获取响应中的 Blob 数据
      const data = response.data as Blob
      const isBlob: boolean = data instanceof Blob && data.size > 0

      if (isBlob) {
        // 直接保存 Blob 数据
        saveAs(data, filename)
      } else {
        // 如果不是有效的 Blob，则尝试获取错误信息
        const resText = await data.text()
        try {
          const rspObj = JSON.parse(resText)
          ElMessage.error(rspObj.message || '导出失败，文件内容无效')
        } catch (parseError) {
          ElMessage.error('导出失败，无法解析文件内容')
        }
      }
      downloadLoadingInstance.close()
    } catch {
      ElMessage.error('导出文件失败！')
      downloadLoadingInstance.close()
    }
  },
  cancelRequest: (url: string | string[]) => {
    return service.cancelRequest(url)
  },
  cancelAllRequest: () => {
    return service.cancelAllRequest()
  }
}
